package com.wmx.yuanyuan.controller;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wmx.yuanyuan.util.BingCrawler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;

/**
 * 爬虫控制器
 *
 * @author wangMaoXiong
 */
@Controller
public class GraspController {

    /**
     * http://localhost:8080/grasp/fetch/陶瓷
     *
     * @param keyword
     * @return
     */
    @ResponseBody
    @GetMapping("/grasp/fetch/{keyword}")
    public String websiteGrasp(@PathVariable String keyword) {
        JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
        ObjectNode objectNode = nodeFactory.objectNode();
        objectNode.put("code", 200);

        System.out.println(keyword);
        String user_home = System.getProperty("user.home");
        File lockFile = new File(user_home + File.separator + "websiteGrasp.lock");
        if (lockFile.exists()) {
            objectNode.put("code", 500);
            objectNode.put("message", "正在抓取[" + keyword + "]，请稍后执行！");
            return objectNode.toString();
        } else {
            try {
                BingCrawler.arrayNode.removeAll();
                lockFile.createNewFile();
                new BingCrawler(keyword, 3).start();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lockFile.delete();
            }
        }
        objectNode.set("data", BingCrawler.arrayNode);
        return objectNode.toString();
    }

}
